/**
 * Description:
 * Class Name:subject1
 * Date:2022/5/19 9:45
 *
 * @author LTisme
 * @version JAVA17
 */
package 疯狂Java讲义.第16章_多线程.课后练习;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

class Printer2{

    public final ReentrantLock lock = new ReentrantLock();
    public final Condition condition = lock.newCondition();
    public int temp = 1;

    public void printNum(){
        for (int i = 1; i <= 52; i++) {
            lock.lock();
            try {
                while (temp % 3 == 0){
                    condition.await();
                }
                System.out.print(i);
                temp++;
                condition.signalAll();
            }
            catch (Exception e){
                e.printStackTrace();
            }
            finally {
                lock.unlock();
            }
        }
    }

    public void printChar(){
        for (char ch = 'A'; ch <= 'Z'; ch++){
            lock.lock();
            try {
                while (temp % 3 != 0){
                    condition.await();
                }
                System.out.print(ch);
                temp++;
                condition.signalAll();
            }
            catch (Exception e){
                e.printStackTrace();
            }
            finally {
                lock.unlock();
            }
        }
    }
}

public class subject1 {
    public static void main(String[] args) {
        var printer = new Printer2();
        new Thread(printer::printNum, "num").start();
        new Thread(printer::printChar, "char").start();
    }
}
